<script lang="ts" setup>
import { Message } from '@arco-design/web-vue';
import { ref } from 'vue';

// 题目类型定义
interface Question {
  id: number;
  questionNum: number;
  content: string;
}

// 题库类型定义
interface QuestionBank {
  id: number;
  questions: Question[];
}

// 表格列配置
const columns = [
  {
    title: '序号',
    dataIndex: 'questionNum',
    width: 80,
    align: 'center',
  },
  {
    title: '题目内容',
    dataIndex: 'content',
  },
  {
    title: '操作',
    slotName: 'operations',
    width: 150,
    align: 'center',
  },
];

// 本地存储键名
const STORAGE_KEY = 'question_banks_data';

// 从本地存储加载题库数据
function loadFromLocalStorage(): QuestionBank[] {
  const data = localStorage.getItem(STORAGE_KEY);
  return data
? JSON.parse(data)
: [
    {
      id: 1,
      questions: [
        { id: 1, questionNum: 1, content: '示例题目1' },
      ],
    },
  ];
}

// 保存题库数据到本地存储
function saveToLocalStorage(banks: QuestionBank[]) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(banks));
}

// 题库数据
const questionBanks = ref<QuestionBank[]>(loadFromLocalStorage());

// 当前激活的题库索引
const activeBankIndex = ref(0);

// 添加题目模态框状态
const showAddModal = ref(false);

// 新题目表单
const newQuestionForm = ref({
  content: '',
});

// 题目ID计数器
let questionIdCounter = 2;

/**
 * 添加题库
 */
function addQuestionBank() {
  const newBankId = questionBanks.value.length + 1;
  questionBanks.value.push({
    id: newBankId,
    questions: [],
  });
  activeBankIndex.value = questionBanks.value.length - 1;
  saveToLocalStorage(questionBanks.value);
  Message.success('题库添加成功');
}

/**
 * 删除当前的题库
 */
function delQuestionBank() {
  if (questionBanks.value.length === 1) {
    Message.error('至少保留一个题库');
    return;
  }
  questionBanks.value.splice(activeBankIndex.value, 1);
  activeBankIndex.value = Math.max(0, activeBankIndex.value - 1);
  saveToLocalStorage(questionBanks.value);
  Message.success('题库删除成功');
}

/**
 * 添加题目
 */
function handleAddQuestion() {
  const currentBank = questionBanks.value[activeBankIndex.value];

  if (!newQuestionForm.value.content.trim()) {
    Message.error('请输入题目内容');
    return;
  }

  currentBank.questions.push({
    id: questionIdCounter++,
    questionNum: currentBank.questions.length + 1,
    content: newQuestionForm.value.content,
  });

  saveToLocalStorage(questionBanks.value);
  Message.success('题目添加成功');
  resetForm();
  showAddModal.value = false;
}

/**
 * 编辑题目
 * @param index 题目索引
 */
function editQuestion(index: number) {
  const currentBank = questionBanks.value[activeBankIndex.value];
  newQuestionForm.value.content = currentBank.questions[index].content;
  showAddModal.value = true;
  // TODO: 实现编辑逻辑
}

/**
 * 删除题目
 * @param index 题目索引
 */
function deleteQuestion(index: number) {
  const currentBank = questionBanks.value[activeBankIndex.value];
  currentBank.questions.splice(index, 1);
  saveToLocalStorage(questionBanks.value);
  Message.success('题目删除成功');
}

/**
 * 重置表单
 */
function resetForm() {
  newQuestionForm.value = {
    content: '',
  };
}
</script>

<template>
  <div class="question-bank-container">
    <!-- 题库管理区域 -->
    <a-tabs v-model:active-key="activeBankIndex" type="rounded">
      <a-tab-pane
        v-for="(bank, index) in questionBanks"
        :key="index"
        :title="`题库${index + 1}`"
      >
        <!-- 题目列表 -->
        <div class="question-list">
          <a-table :data="bank.questions" :columns="columns" bordered stripe :pagination="false" row-key="id">
            <template #operations="{ rowIndex }">
              <a-space>
                <a-button type="text" @click="editQuestion(rowIndex)">编辑</a-button>
                <a-button type="text" status="danger" @click="deleteQuestion(rowIndex)">删除</a-button>
              </a-space>
            </template>
          </a-table>

          <!-- 添加题目按钮 -->
          <a-button type="outline" long class="add-btn" @click="showAddModal = true">
            添加题目
          </a-button>
        </div>
      </a-tab-pane>
    </a-tabs>

    <!-- 添加题库按钮 -->
    <a-button
      type="primary"
      class="add-bank-btn"
      @click="addQuestionBank"
    >
      添加题库
    </a-button>
    <!-- 删除题库 -->
    <a-popconfirm content="真删吗?" @ok="delQuestionBank">
      <a-button
        type="primary"
        class="add-bank-btn ml-10px"
      >
      删除题库
      </a-button>
    </a-popconfirm>

    <div class="mt-20px">
      <RouterLink to="/">
        <a-button type="dashed">返回首页</a-button>
      </RouterLink>
    </div>

    <!-- 添加题目模态框 -->
    <a-modal
      v-model:visible="showAddModal"
      title="添加题目"
      @ok="handleAddQuestion"
      @cancel="resetForm"
    >
      <a-form :model="newQuestionForm">
        <a-form-item field="content" label="题目内容">
          <a-textarea v-model="newQuestionForm.content" placeholder="请输入题目内容" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.question-bank-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  height: 100%;
}

.question-list {
  margin-top: 16px;
}

.add-btn {
  margin-top: 16px;
}

.add-bank-btn {
  margin-top: 20px;
}
</style>
